#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
Model for blog on gae. 

Data structure is a tree:

 + BlogDump (describes one blog as a collection of 
 |           entries from one user uner one name)
 |
 +-+BlogEntry (one unique entry. Has title and date, 
   |           can have Comments attached)
   |
   +-+Comment (a comment to a BlogEntry, has an author, 
     |         date)
     +Comment
     ...   

"""
__author__ = 'Cezary Statkiewicz <c.statkiewicz@gmail.com>'


import re

from google.appengine.ext import ndb


_replace_chars = re.compile(r'[\s\+_\-\W]+', re.I)

def slugify(field_name):
    """
    Make a slug from an attribute of an object:

    >>> class A(ndb.Model):
    ...     name = ndb.StringProperty()
    ...     slug = slugify('name')

    >>> a = A(name='Some name')
    >>> a.put()
    >>> a.slug
    'some_name'

    """
    def _slugify(obj):
        val = '%s' % (getattr(obj, field_name, None) or '')
        if val:
            # remove non-letter chars, clear endings from any extra _
            val = _replace_chars.sub('_', val.lower()).strip('_')
        return val

class BlogDump(ndb.Model):
    """
        Root 
    """
    name = ndb.StringProperty(required=True)
    slug = ndb.ComputedProperty(slugify('name'))
    owner = ndb.UserProperty(required=True)
    active = ndb.BooleanProperty(required=True)
    created = ndb.DateTimeProperty(required=True, auto_now_add=True)



class Entry(ndb.Model):
    title = ndb.StringProperty(required=True)
    content = ndb.TextProperty(required=True)
    created = ndb.DateTimeProperty(required=True, auto_now_add=True)
    published = ndb.DateTimeProperty(required=True)


class Comment(ndb.Model):
    author = ndb.UserProperty(required=True)
    created = ndb.DateTimeProperty(required=True, auto_now_add=True)
    active = ndb.BooleanProperty(required=True)
    content = ndb.TextProperty(required=True)




